package com.ihcil.forecast.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ihcil.forecast.demo.pojo.Models;
import com.ihcil.forecast.demo.mapper.ModelsMapper;
import com.ihcil.forecast.demo.service.ModelsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author @baseException
 * @since 2022-11-11
 */
@Slf4j
@Service
public class ModelsServiceImpl extends ServiceImpl<ModelsMapper, Models> implements ModelsService {

    @Transactional
    @Override
    public void save2DbAndServer(Models models, MultipartFile file, String filePath) throws IOException {
        LambdaQueryWrapper<Models> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Models::getUserName, models.getUserName());
        int curIdCount = this.count(wrapper);

        // 规定一个用户只能上传一个模型
        if (curIdCount > 0) {
            // 先删除服务器端实际存储的用户模型
            Models oriModels = this.getOne(wrapper);
            boolean flag = DeleteFile(oriModels.getModePath(), oriModels.getUserName());
            if (flag) {
                //再更新数据库数据
                this.update(models, wrapper);
                log.info("{}用户模型更新成功...", models.getUserName());
            }
        }else {
            this.save(models);
        }
        file.transferTo(new File(filePath));
    }

    public boolean DeleteFile(String sPath, String userName) {
        File file = new File(sPath);
        boolean flag = false;

        if (file.isFile() && file.exists()) {
            flag = file.delete();
            if (flag) {
                log.info("{} 用户模型删除成功，可以进行更新", userName);
            }
        }

        return flag;
    }
}
